package com.dongdong.bookstore.module.ums.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dongdong.bookstore.common.api.CommonPage;
import com.dongdong.bookstore.common.api.ResultData;
import com.dongdong.bookstore.common.api.ReturnCode;
import com.dongdong.bookstore.common.exception.ApiException;
import com.dongdong.bookstore.common.exception.Asserts;
import com.dongdong.bookstore.module.ums.model.Admin;
import com.dongdong.bookstore.module.ums.model.Menu;
import com.dongdong.bookstore.module.ums.model.Role;
import com.dongdong.bookstore.module.ums.service.AdminLoginLogService;
import com.dongdong.bookstore.module.ums.service.AdminService;
import com.dongdong.bookstore.module.ums.service.MenuService;
import com.dongdong.bookstore.module.ums.service.RoleService;
import com.dongdong.bookstore.module.ums.viewmodel.AdminLoginParam;
import com.dongdong.bookstore.module.ums.viewmodel.AdminRegistParam;
import com.dongdong.bookstore.module.ums.viewmodel.AdminWithLastLoginTime;
import com.dongdong.bookstore.module.ums.viewmodel.UpdateAdminPasswordParam;
import com.dongdong.bookstore.security.model.UserCategory;
import com.dongdong.bookstore.utils.IpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 管理员表 前端控制器
 * </p>
 *
 * @author chiangkai
 * @since 2021-10-20
 */
@Api(tags = "管理员模块")
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private AdminService adminService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private AdminLoginLogService adminLoginLogService;


    @Value("${spring.profiles.active}")
    private String ENV;

    @ApiOperation("注册管理员")
    @PostMapping("/register")
    public ResultData<Admin> register(@RequestBody @Validated AdminRegistParam param) {
        Admin admin = adminService.register(param);
        admin.setPassword("");
        return ResultData.ok("注册成功", admin);
    }

    @ApiOperation("判断管理员存在 存在 FALSE 不存在 TRUE")
    @PostMapping("/judgeAdminExist")
    public String judgeAdminExist(@RequestParam(value = "username") String username) {
        adminService.judgeAdminExist(username);
        return "管理员不存在";
    }

    @ApiOperation("管理员登录操作")
    @PostMapping("/login")
    public Map<String, String> login(@RequestBody @Validated AdminLoginParam param, HttpServletRequest request) {
        String token = adminService.login(param.getUsername(), param.getPassword());
        adminLoginLogService.addAdminLoginLog(param.getUsername(), IpUtil.getIpAddr(request));
        HashMap<String, String> map = new HashMap<>();
        map.put("token", token);
        map.put("tokenHead", UserCategory.ADMIN.ordinal() + tokenHead);
        if (ENV.equals("dev")) {
            map.put("allToken", map.get("tokenHead") + map.get("token"));
        }
        return map;
    }

    @ApiOperation("管理员口令刷新")
    @GetMapping("/reflashToken")
    public Map<String, String> reflashToken(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        String refreshToken = adminService.refreshToken(token);
        HashMap<String, String> map = new HashMap<>();
        map.put("token", refreshToken);
        map.put("tokenHead", UserCategory.ADMIN.ordinal() + tokenHead);
        return map;
    }

    @ApiOperation("删除指定用户信息")
    @PostMapping("/delete/{id}")
    public String delete(@PathVariable Long id, Principal principal) {
        String username = null;
        if (principal != null) {
            //admin 5 + : 1  = 6
            username = principal.getName().substring(6);
        } else {
            Asserts.fail(ReturnCode.NO_TOKEN);
        }
        boolean success = adminService.delete(id, username);
        Asserts.isFalse(success, "删除管理员失败");
        return "删除管理员成功";
    }

    @GetMapping("/logout")
    @ApiOperation("登出接口")
    public String logout() {
        return "登出成功";
    }

    @ApiOperation("获取管理员信息")
    @GetMapping("/info")
    public Map<String, Object> getAdminInfo(Principal principal) {
        if (principal == null) {
            throw new ApiException(ReturnCode.NO_TOKEN);
        }
        Admin admin = adminService.getAdminByUsername(principal.getName().substring(principal.getName().indexOf(":") + 1));
        Map<String, Object> map = new HashMap<>();
        map.put("username", admin.getUsername());
        map.put("icon", admin.getIcon());
        List<Menu> menuList = menuService.getMenuListByAdminId(admin.getId());
        map.put("menus", menuList);
        List<Role> roles = roleService.getLoleListByAdminId(admin.getId());
        map.put("roles", roles);
        return map;
    }

    @ApiOperation("根据用户名或直接获取用户列表分页")
    @GetMapping("/list")
    public CommonPage<AdminWithLastLoginTime> list(@RequestParam(value = "keyword", required = false) String keyword,
                                                   @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                   @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        IPage<AdminWithLastLoginTime> page = adminService.list(keyword, pageSize, pageNum);
        return CommonPage.restPage(page);

    }

    @ApiOperation("通过adminID获取用户信息")
    @GetMapping("/{id}")
    public Admin getAdminById(@PathVariable("id") Long id) {
        return adminService.getById(id);
    }

    @ApiOperation("修改指定用户信息")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    public String update(@PathVariable Long id, @RequestBody Admin admin) {
        boolean success = adminService.update(id, admin);
        if (success) {
            return "更新成功";
        } else {
            Asserts.fail("更新失败");
        }
        return null;
    }

    @ApiOperation("通过旧密码更新密码接口")
    @PostMapping("/updatePassword")
    public String updatePassword(@Validated @RequestBody UpdateAdminPasswordParam updateAdminPasswordParam) {
        adminService.updatePassword(updateAdminPasswordParam);
        return "更新密码成功";
    }

    @ApiOperation("更新管理员用户角色")
    @PostMapping("/role/update")
    public String updateRole(
            @RequestParam("adminId") Long adminId,
            @RequestParam("roleIds") List<Long> roleIds
    ) {
        roleService.updateRole(adminId, roleIds);
        return "更新成功";
    }

    @ApiOperation("获取用户的角色")
    @PostMapping("/role/{adminId}")
    public List<Role> getRoleList(@PathVariable Long adminId) {
        return adminService.getRoleList(adminId);
    }
}
